package com.yuxi.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.yuxi.common.SkJsonResult;
import com.yuxi.common.StringUtil;
import com.yuxi.common.redis.RedisUtil;
import com.yuxi.common.token.AdminToken;
import com.yuxi.common.token.JwtsUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author sunke
 * @Date 2020/12/21 14:12
 * @description
 */
@Component(value = "rightsInterceptor")
public class RightsInterceptor extends LoginInterceptor {


    //白名单
    @Value("${whiteList}")
    private String[] whiteList;

    @Resource
    private RedisUtil redisUtil;


    public static void noRights(HttpServletResponse response) {
        response.setContentType("application/json;charset = UTF-8");
        String msg = "用户无权限";

        try {
            int code = 88888;

       /*     response.setContentType("application/json;charset = UTF-8");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type, Authorization," + JwtsUtil.ADMIN_HEADER_KEY);
*/
            SkJsonResult skJsonResult = new SkJsonResult().setFail(msg);
            skJsonResult.setErrorCode(code);

            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(skJsonResult));
            writer.flush();
            writer.close();


        } catch (Exception e) {

        }

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if (!super.preHandle(request, response, handler)) {
            return false;
        }


        String header = request.getHeader(JwtsUtil.ADMIN_HEADER_KEY);

        AdminToken staffToken = getJwtsUtil().parseAdminToken(header);


        String action = request.getRequestURI();


        if (StringUtil.isNotObjEmpty(whiteList)) {

            for (String white : whiteList) {
                if (action.toUpperCase().indexOf(white.split("\\?")[0].toUpperCase()) >= 0) {
                    return true;
                }

            }


        }


        if (StringUtil.isObjEmpty(redisUtil.getRightsBack(staffToken.getAdminId()))) {
            noRights(response);
            return false;
        }


        for (String v : redisUtil.getRightsBack(staffToken.getAdminId())) {

            if (action.toUpperCase().indexOf(v.split("\\?")[0].toUpperCase()) >= 0) {
                return true;
            }
        }
        noRights(response);
        return false;


    }


}
